package org.phalanx.map;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.phalanx.map.xml.PhalanxMapXMLWriter;
import org.phalanx.zip.ZipFileArchiveWriter;

public class PhalanxMapWriter {
	private PhalanxMap writeMap;
	boolean defaultTileSet = true;
	private String createdBy;
	
	public PhalanxMapWriter(PhalanxMap map, boolean usingDefaultTileSet){
		writeMap = map;
		defaultTileSet = usingDefaultTileSet;
	}
	
	public boolean writeMapPackageOut(String fileName){
		boolean isSuccess = false;
		
		try {
			ZipFileArchiveWriter zipFileOut = new ZipFileArchiveWriter();
			zipFileOut.setZipFileByName(fileName);
			
			zipFileOut.openArchive();
			writeMapTextFile(zipFileOut);
			if (!defaultTileSet){
				writeAlternativeTileSet(zipFileOut);
			}
			
			zipFileOut.close();
		} catch (IOException ie) {}
		
		return isSuccess;
	}
	
	public void setCreatedBy(String createdBy){
		this.createdBy = createdBy;
	}
	
	private void writeMapTextFile(ZipFileArchiveWriter zipOut) throws IOException {
		PhalanxMapXMLWriter xmlOut = new PhalanxMapXMLWriter(writeMap, defaultTileSet, createdBy);
		String xmlData = xmlOut.writeOutXML();
		
		zipOut.writeStringDataToArchive("map.xml", xmlData);
	}
	
	private void writeAlternativeTileSet(ZipFileArchiveWriter zipOut) throws IOException {
		String archivePath = writeMap.getMapTileSet().getTileSetArchiveFile();
		
		File tileSetFile = new File(archivePath);
		byte[] copyBytes = new byte[(int)tileSetFile.length()];
		
		if (tileSetFile.exists()){
			DataInputStream dIn = new DataInputStream(new FileInputStream(tileSetFile));
		
			dIn.readFully(copyBytes);
			
			dIn.close();
			
			String[] bits = writeMap.getMapTileSet().getCanonicalFilePath().split("/");
			
			if (bits.length == 0){
				bits = writeMap.getMapTileSet().getCanonicalFilePath().split("\\");
			}
			
			if (bits.length > 1){
				String directoryStr = "";
				for (int i = 0; i < bits.length - 1; i++){
					directoryStr += bits[i] + "/";
					zipOut.writeDirectory(directoryStr);
				}
				
				zipOut.writeBinaryDataToArchive(directoryStr + bits[bits.length - 1], copyBytes);
			}
			else if (bits.length == 1){
				zipOut.writeBinaryDataToArchive(bits[bits.length - 1], copyBytes);
			}
		}
	}
}
